package com.astoolkit.onair.workflow
{
	import com.astoolkit.onair.api.IRunnable;
	import com.astoolkit.onair.vo.AirModuleConfig;
	import com.astoolkit.workflow.core.BaseTask;
	
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.events.Event;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.system.ApplicationDomain;
	import flash.system.LoaderContext;
	import flash.utils.ByteArray;
	
	import mx.core.IFlexModuleFactory;
	
	public class LoadCachedModuleTask extends BaseTask
	{
		[InjectPipeline]
		public var config : AirModuleConfig;
		
		override public function begin() : void
		{
			super.begin();
			if( !config )
			{
				fail( "No config passed to this task" );
				return;
			}
			try
			{
				var fileStream : FileStream = new FileStream();
				fileStream.open( 
					config.localRepository.resolvePath( config.executable ), FileMode.READ ); 
				
				// Read SWF bytes into byte array and close file
				var bytes : ByteArray = new ByteArray();
				fileStream.readBytes( bytes );
				fileStream.close();
				
				var moduleLoader : Loader = new Loader();
				var context : LoaderContext = new LoaderContext();
				context.allowLoadBytesCodeExecution = true;
				context.applicationDomain = ApplicationDomain.currentDomain;    
				
				//bytes from local file (module file is stored in app storage)
				moduleLoader.contentLoaderInfo.addEventListener( Event.COMPLETE, onModuleLoaded );
				moduleLoader.loadBytes( bytes, context );
				
			}
			catch( error : Error )
			{
				fail( "Error reading cached module" );
			}
			
		}
		
		private function onModuleLoaded( inEvent : Event ) : void
		{
			if( inEvent.type=="progress") return;
			var moduleLoader : LoaderInfo = LoaderInfo( inEvent.target );
			moduleLoader.content.addEventListener( "ready", onModuleReady );
		}
		
		private function onModuleReady( inEvent : Event ) : void 
		{
			var loaderInfo : LoaderInfo = inEvent.target.loaderInfo;
			var module : IRunnable;
			try	
			{    
				var factory : IFlexModuleFactory = 
					IFlexModuleFactory( inEvent.target );
				module = factory.create() as IRunnable;
				module.config = config;
			}
			catch ( error : Error )
			{	
				fail( "Failed loading module" );
			}
			_pipelineData = module;
			complete();
		}
		
				
		
	}
}